package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import model.TravelPath;

public class UrlUtils {

	/**
	 * Method allowing the reading of a HTTP server response and copying the contents of the 
	 * said response into a temporary file (local to project).
	 * 
	 * @param tempFile File name where server response content will be stored
	 * @param urlStr String representing url to be used for HTTP connection
	 * @return boolean
	 */
	public static boolean readCopyHttpResponse(final String tempFile, final String urlStr){
		boolean successful = true;
		URL url = null;
		URLConnection urlConn = null;
		BufferedReader in = null;
		FileWriter fw = null;
		BufferedWriter out = null;
		
		try{
			// create URL object with urlStr
			// and establish connection 
			url = new URL(urlStr);
			urlConn = url.openConnection();
			in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
	        
			File file = new File(tempFile);
			if(!file.exists()){
				file.createNewFile();
			}
			
			fw = new FileWriter(file);
			out = new BufferedWriter(fw);
			
			String inputLine;
			
			// read input from inpur strean and copy
			// contents into temporary file
			while ((inputLine = in.readLine()) != null) {
				out.write(inputLine);
			}
			
		}
		catch(MalformedURLException mExc){
			mExc.printStackTrace();
		}
		catch(IOException iExc){
			iExc.printStackTrace();
		}
		finally{
			try{
				in.close();
				out.close();
			}
			catch(IOException ioExc){
				ioExc.printStackTrace();
			}
		}
		
		return successful;
	}
	
	/**
	 * Method allowing the creation of a url string to be used when sending a http request
	 * to the Google Static Maps web service.
	 *  
	 * @param tp TravelPath object acting as a Transfer Object that aggregates all 
	 *           necessary information pertaining to a specified trajectory. 
	 * @return String
	 */
	public static String getUrlStrStaticMap(TravelPath tp){
		StringBuilder sb = new StringBuilder();
		sb.append("http://maps.google.com/maps/api/staticmap?center=");
		sb.append(tp.getWayPoint());
		sb.append("&size=512x512&maptype=roadmap&markers=color:blue%7Clabel:S%7C");
		sb.append(tp.getStartLocation());
		sb.append("&markers=color:green%7Clabel:W%7C");
		sb.append(tp.getWayPoint());
		sb.append("&markers=color:red%7Ccolor:red%7Clabel:E%7C");
		sb.append(tp.getEndLocation());
		sb.append("&sensor=false&path=");
		sb.append(tp.getStartLocation()+"|");
		sb.append(tp.getWayPoint()+"|");
		sb.append(tp.getEndLocation());
		return formatBasicUrl(sb.toString());
		
	}
	
	/**
	 * Method allowing the creation of a url string to be used when sending a http request
	 * to the Google Directions web service.
	 *  
	 * @param start String representing start address
	 * @param end String representing end address
	 * @param wayPoint String representing intermediate address
	 * @return String
	 */
	public static String getDrivingDirectionsUrlStr(String start, String end, String wayPoint){
		StringBuilder sb = new StringBuilder();
		sb.append("http://maps.googleapis.com/maps/api/directions/xml?origin=");
		sb.append(start);
		sb.append("&destination=");
		sb.append(end);
		sb.append("&waypoints=");
		sb.append(wayPoint);
		sb.append("&optimize=true&sensor=false");
		return formatBasicUrl(sb.toString());
	}
	
	/**
	 * Method allowing basic URL formatting. The current fonctionality is limited to escaping
	 * url whitespaces with %20.
	 * 
	 * @param urlStr String that is to be formatted
	 * @return String Formatted url string
	 */
	private static String formatBasicUrl(String urlStr){
		//urlStr = urlStr.replaceAll("&", "&amp;");
		urlStr = urlStr.replaceAll(" ", "%20");
		return urlStr;
	}
	
	/**
	 * Private constructor. UrlUtils class contains only static methods, therefore there is no need
	 * to allow class instanciation. Modified version of a Singleton where instance retrieval
	 * is not deemed necessary.
	 */
	private UrlUtils(){}
	
	
	
}

